<?php

namespace App\Http\Controllers\Users;

use App\Models\Admin;
use App\Models\User;
use Carbon\Carbon;
use EasyWeChat\Factory;
use EasyWeChat\Work\Application;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Hashing\BcryptHasher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class WechatController extends BaseController
{


    /**
     * 验证开发者
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request){

        $app = Factory::officialAccount(config('wechat.easy_wechat'));

//        $app->server->push(function ($message) {
//            return "您好！欢迎使用 EasyWeChat!";
//        });

//        $this->addMenu($app);

        return $app->server->serve();

    }

    /**
     * 获取用户token
     * @param Request $request
     * @param int $type
     * @return array|\Illuminate\Http\JsonResponse|string
     * @throws \Exception
     */
    public function token(Request $request,$type=0)
    {
        $expiresAt = Carbon::now()->addHours(2);

        $token = $request->header('token');
//        $type = $request->header('type');//内部调用
        if ($token && Cache::has($token)) {
            $tokenInfo = Cache::get($token);
            Cache::put($token, $tokenInfo, $expiresAt);
            if($type==1){
                return $token;
            }
            return response()->json([
                'token' => $token,
                'expires_in' => 7200,
                'url' =>  config('app.url').'/api/user/oauth'
            ]);
        }
        $token = md5(uniqid('jccj', true) . random_int(1, 9999));

        Cache::put($token, $token, $expiresAt);
        if($type==1){
            return $token;
        }
        return response()->json([
            'token' => $token,
            'expires_in' => 7200,
            'url' => config('app.url').'api/user/oauth'
        ]);
    }

    /**
     * 没调用
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request)
    {
        $token = $request->header('token', '');

        $user = Admin::findUser($token);

        $info = $user;

        return response()->json($info);

        /*

        $user = DB::table('user')->where('token', $token)->first();


        if (!$user) {
            return response()->json(['error'=>'未找到用户信息'], 401);
        }

        $userInfo = DB::table('user_info')
            ->where('uid', $user->id)
            ->select(['uid', 'openid', 'nickname', 'province', 'city', 'country', 'portrait', 'sex'])
            ->first();

        if (!$userInfo) {
            return response()->json(['error'=>'未找到用户信息'], 401);
        }


        $info = [
            'uid'       => $userInfo->uid,
            'openid'    => $userInfo->openid,
            'nickname'  => $userInfo->nickname,
            'province'  => $userInfo->province,
            'city'      => $userInfo->city,
            'country'   => $userInfo->country,
            'portrait'  => $userInfo->headimgurl,
            'sex'       => $userInfo->sex
        ];

        return response()->json($info);

        */

    }
    /**
     * 网页授权
     * @param string token
     * @param string redirect 授权后跳转地址
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function oauth(Request $request)
    {

        $token = $request->input('token', '');
        $redirect = $request->input('redirect', '');

        \Log::info($redirect.'----------------------');

        session()->put('token', $token);
        session()->put('redirect', $redirect);

        \Log::info($redirect.'+++++++++++++++++++++++++');

//        return $this->json(false,'test',[
//            'token'=>$token,
//            'redirect'=>$redirect,
//            'session_token'=>session('token'),
//            'session_redirect'=>session('redirect'),
//        ]);

        $config = config('wechat.easy_wechat');

        $config['oauth']['callback'] = config('app.url')."/api/user/oauthNotice/{$token}?redirect=".$redirect;

        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        $response = $oauth->scopes(['snsapi_userinfo'])
            ->redirect();
        \Log::info('88888888'.$response);
        return $response;
    }

    /**
     * 授权回调地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function oauthNotice(Request $request,$token)
    {

        if(session('token')){
            $token = session('token');
        }
        $redirect = session('redirect');

        if(!$redirect){

            $redirect = $request->get('redirect');
        }


        try{
            $config = config('wechat.easy_wechat');

//            $config['oauth']['callback'] = "/api/user/oauthNotice/{$token}";

            $app = Factory::officialAccount($config);
            $oauth = $app->oauth;
            // 获取 OAuth 授权结果用户信息
            $user = $oauth->user();
            if(!$user){
                return $this->json(false, '授权失败');
            }
        }catch (AuthenticationException $afe){
            if ($afe->getCode() == -1 ) {
                return $this->json(false, '授权失败');
            };
            return $this->json(false, '授权失败');
        }

        $user = $user->getOriginal();

        \Log::info($redirect.'+++++++*****************+++++++++');

        \Log::info($user);

        //检测用户
        if(!Admin::checkExists($user['openid'])){

            $insert = [
                'nickname'=>$user['nickname'],
                'password'=>bcrypt('123123'),
                'avatar_url'=>$user['headimgurl'],
                'gender'=>$user['sex'],
                'openid'=>$user['openid'],
                'token'=>$token,
                'sign_type'=>0,
                'mobile'=>'0',
                'email'=>'',
                'dept'=>'0'
            ];
            //创建用户
            $in = Admin::add2($insert);

            \Log::info($in);
//            return $this->json(false,'test1',[Admin::checkExists($user['openid']),
//                $in]);

        }else{

            $update = [
                'avatar_url'=>$user['headimgurl'],
                'token'=>$token,
            ];
            //修改用户
            $getUser = Admin::setUser($user['openid'],$update);
        }

        //test
//        return $this->json(false,'test',[Admin::checkExists($user['openid'])]);

        return redirect( urldecode($redirect));

        /*
        if (DB::table('user')->where('openid', $user['openid'])->exists()) {

            $uid = DB::table('user')->where('openid', $user['openid'])->pluck('id');
            DB::table('user')->where('openid', $user['openid'])->update(['token' => $token]);

            DB::table('user_info')->where('uid', $uid)
                ->update([
                    'nickname' => $user['nickname'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'country' => $user['country'],
                    'portrait' => $user['headimgurl'],
                    'sex' => $user['sex']
                ]);


            return redirect(urldecode($redirect));
        }

        try {
            DB::transaction(function () use (&$user, &$token, $request) {
                $uid = DB::table('user')->insertGetId([
                    'openid' => $user['openid'],
                    'token' => $token,
                    'register_ip' => $request->ip(),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ]);
                DB::table('user_info')->insert([
                    'uid' => $uid,
                    'openid' => $user['openid'],
                    'nickname' => $user['nickname'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'country' => $user['country'],
                    'portrait' => $user['headimgurl'],
                    'sex' => $user['sex'],
                    'created_at'=>date('Y-m-d H:i:s'),
                    'updated_at'=>date('Y-m-d H:i:s'),
                ]);
                DB::table('user_money')->insert([
                    'uid'=>$uid,
                ]);
                $get = DB::table('user_lai')
                    ->where('openid',$user['openid'])
                    ->first();
                if($get){
                    DB::table('user_lai')
                        ->where('openid',$user['openid'])
                        ->update(['uid'=>$uid]);
                    DB::table('user_info')
                        ->where('uid',$uid)
                        ->update([
                            'user_id'=>$get->user_id,
                            'shop_id'=>$get->shop_id,
                            'source'=>$get->type,
                        ]);
                }

                //送优惠券


            });
        }catch (\Exception $exception) {

            dd($exception);

        }

        return redirect( urldecode($redirect));

        */
    }

    /**
     * 微信配置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jssdk(Request $request){
        $url = $request->input('url', '');
        $APIs = $request->input('APIs', []);

        $config = config('wechat.easy_wechat');
        $app = Factory::officialAccount($config);

        $app->jssdk->setUrl($url);
        $config = $app->jssdk->buildConfig($APIs, false, false, false);

        return response()->json($config);
    }


    /**
     * 模板消息推送
     * @param $openid 用户的openid
     * @param $title 标题
     * @param $content
     * @param $keyword2
     * @param int $type 1 会议通知 2 3 4 5 6 7 8 9
     * @return array|bool|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function _msgPush($openid,$data,$type=1){

        if(!$data){

            return false;
        }

        $app = Factory::officialAccount(config('wechat.easy_wechat'));

        $datas = [];

        switch ($type){
            case 1://会议通知
                $datas = [
                    'template_id' => 'wz7Sf6BdpY3zPrhEHSF5gAu2t19CS9gxW573FoTTTcA',
                    'url' => 'http://www.cqukon.com/wechat/',
//                    'touser' => $openid,
//                    'data'=>$data
//                    'data'=>[
//                        'first'=>['value'=>$data['first']],
//                        'keyword1'=>['value'=>$data['keyword1']],
//                        'keyword2'=>['value'=>$data['keyword2']],
//                        'remark'=>['value'=>$data['remark']]
//                    ]
                ];
                break;
            case 2://审核结果通知

                $datas = [
                    'template_id' => 'mo2R5yD4jYaWp81imeP6PwLcpCjadTtcd1z2tSp6YLk',
                    'url' => 'http://www.cqukon.com/wechat/',
//                    'data'=>[
//                        'first'=>['value'=>''],
//                        'keyword1'=>['value'=>''],
//                        'keyword2'=>['value'=>''],
//                        'remark'=>['value'=>''],
//                    ]
                ];
                break;
            case 3://请假审核通知
                $datas = [
                    'template_id' => 'jJQMKZr4lJn7ZA1ys2jB4yKT1jdQgPi-lgFITxC76vU',
                    'url' => 'http://www.cqukon.com/wechat/',
//                    'data'=>[
//                        'first'=>['value'=>''],
//                        'keyword1'=>['value'=>''],
//                        'keyword2'=>['value'=>''],
//                        'remark'=>['value'=>''],
//                    ]
                ];
                break;
            case 4://审核结果提醒
                $datas = [
                    'template_id' => 'gzIo2NoJDa9sCKPomRUs-2hnlO49IVfCJTRWB0zMuSg',
                    'url' => 'http://www.cqukon.com/wechat/',
                ];
                break;
            case 5://会议审核提醒
                $datas = [
                    'template_id' => 'cB93eb-JoDrRADXl5rgJrhT31IgSnaZlTXGb-B2LIpY',
                    'url' => 'http://www.cqukon.com/wechat/',
//                    'data'=>[
//                        'keyword4'=>['value']
//                    ]
                ];
                break;
            case 6://抽查检查通知
                $datas = [
                    'template_id' => 'bCDYlYc7-Y05RmAuIeT1MDwV6Upj3bATyTmxtdyEnVE',
                    'url' => 'http://www.cqukon.com/wechat/',
//                    'data'=>[
//                        'keyword2'=>['value']
//                    ]
                ];
                break;
        }

        if(!$datas){
            return false;
        }

        $datas['touser'] = $openid;
        $datas['data'] = $data;

        $send = $app->template_message->send($datas);

        return $send;

        \Log::info($send);

        return true;


    }

}
